package com.mvvm.start.main.mvvm.v.fragment.main

import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.mvvm.start.base.base.BaseFragment
import com.mvvm.start.base.utils.CommonUtils
import com.mvvm.start.base.utils.loge
import com.mvvm.start.base.utils.toast
import com.mvvm.start.main.databinding.FragmentMarketBinding
import com.mvvm.start.main.mvvm.v.adapter.MarketPagingListAdapter
import com.mvvm.start.main.mvvm.vm.MarketFragmentViewModle
import java.lang.Exception


/**
 * @author lmy
 * @功能: 市场Fragment
 * @Creat 12/23/20 12:08 PM
 * @Compony 465008238@qq.com
 */
class MarketFragment : BaseFragment<MarketFragmentViewModle, FragmentMarketBinding>() {

    private val marketPagingListAdapter = MarketPagingListAdapter()

    override fun initViews() {
        isFirstRequest = false
        viewBinding.toolbar.setPadding(0, CommonUtils.getStatusBarHight(requireContext()), 0, 0)
        viewBinding.marketViewModle = mViewModel
        initLivaData()
        initRecyclerview()
    }
    private fun initLivaData() {
        initData()
    }
    private fun initRecyclerview() {
        viewBinding.smartlayout.setEnableLoadMore(false)//禁用smartlayout的上啦加载
        viewBinding.rvMarket.apply {
            layoutManager = LinearLayoutManager(activity)
            adapter = marketPagingListAdapter
        }
        marketPagingListAdapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    "addLoadStateListener :LoadState NotLoading ".loge()
                    viewBinding.rvMarket.visibility = View.VISIBLE
                }
                is LoadState.Loading -> {
                    "addLoadStateListener :LoadState Loading ".loge()
                    viewBinding.rvMarket.visibility = View.INVISIBLE
                }
                is LoadState.Error -> {
                    "addLoadStateListener :LoadState Error ".loge()
                    val state = it.refresh as LoadState.Error
                    "Load Error: ${state.error.message}".toast()
                }
            }
        }
    }

    override fun initObserve() {
    }
    override fun initData() {
        try {
            mViewModel.getMarketListPagingData().observe(viewLifecycleOwner) {
                lifecycleScope.launchWhenCreated {
                    marketPagingListAdapter.submitData(it)
                }
            }
            mViewModel.refresh.observe(viewLifecycleOwner){
                if (!it){
                    marketPagingListAdapter.refresh()
                }
            }
        } catch (e: Exception) {
        }
    }
}